package com.soft.base.protocol;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
public class Result implements Serializable {
    @Setter
    @Getter
    int code;
    @Getter
    @Setter
    String msg;
    @Getter
    @Setter
    Object data = null;

    public static Result build(int code, String msg) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    public static Result build(int code, String msg, Object data) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }

    public static class Builder {

        private Result result = new Result();

        public Builder code(int code) {
            result.setCode(code);
            return this;
        }

        public Builder msg(String msg) {
            result.setMsg(msg);
            return this;
        }

        public Builder data(Object data) {
            result.setData(data);
            return this;
        }

        public Builder dataPut(String key, Object value) {
            if (null == result.getData()) {
                result.data = new HashMap<String, Object>(128);
            }
            ((Map<String, Object>) result.data).put(key, value);
            return this;
        }

        public Result build() {
            return result;
        }
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    public static Builder builder() {
        return new Builder();
    }

    public static Builder builder(int code, String msg) {
        return new Builder().code(code).msg(msg);
    }

    public static Result fromJson(String json) {
        return JSONObject.parseObject(json, Result.class);
    }
}
